package pers.xhh.shopapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiOrderDao;
import pers.xhh.shopapi.entity.MiOrderEntity;
import pers.xhh.shopapi.entity.MiOrderItemEntity;
import pers.xhh.shopapi.entity.MiWareEntity;
import pers.xhh.shopapi.exception.MiException;
import pers.xhh.shopapi.service.MiOrderItemService;
import pers.xhh.shopapi.service.MiOrderService;
import pers.xhh.shopapi.service.MiWareService;
import pers.xhh.shopapi.util.DateUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiOrderServiceImpl extends ServiceImpl<MiOrderDao, MiOrderEntity> implements MiOrderService {

    @Autowired
    MiOrderItemService miOrderItemService;

    @Autowired
    MiWareService miWareService;

    @Override
    public Mi updateOrderStatus(Integer orderId, int code) {
        MiOrderEntity miOrderEntity = new MiOrderEntity();
        miOrderEntity.setId(orderId);
        miOrderEntity.setStatus(code);
        boolean b = this.updateById(miOrderEntity);
        if(b){
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), "更新成功!");
        } else {
            return Mi.error(ResultCode.ERROR1207.getMessage(), ResultCode.ERROR1207.getStatus());
        }
    }

    @Override
    public Mi allOrder(Integer pagenum, Integer pagesize) {
        if(pagenum != null && pagesize != null){
            if(pagenum <=0 || pagesize <= 0){
                return Mi.error(ResultCode.ERROR1204.getMessage(), ResultCode.ERROR1204.getStatus());
            }
            // 如果参数不为空,分页
            IPage<MiOrderEntity> page = new Page<>(pagenum, pagesize);
            this.page(page, null);

            List<MiOrderEntity> records = page.getRecords();
            // 在根据order查询子项
            for (MiOrderEntity record : records) {
                String orderSn = record.getOrderSn();
                List<MiOrderItemEntity> orderItemEntities = miOrderItemService.list(new QueryWrapper<MiOrderItemEntity>().eq("order_sn", orderSn));
                record.setTime(DateUtils.formatDate(record.getCreateTime()));
                record.setChildren(orderItemEntities);
            }
            long total = page.getTotal();
            long current = page.getCurrent();
            long size = page.getSize();

            Map<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("current", current);
            map.put("size", size);
            map.put("items", records);

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }
        List<MiOrderEntity> user_id =
                this.list(null);
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), user_id);
    }

    @Transactional
    @Override
    public Mi cancelOrder(Integer orderId) {
        if(orderId == null){
            return Mi.error(ResultCode.ERROR1204.getMessage(), ResultCode.ERROR1204.getStatus());
        }
        MiOrderEntity byId = this.getById(orderId);
        if(byId != null){
            String orderSn = byId.getOrderSn();
            Integer id = byId.getId();
            // 删除订单项和订单
            boolean b = this.removeById(id);
            if(b){
                // 取消库存锁定
                List<MiOrderItemEntity> orderItemEntities =
                        miOrderItemService.list(new QueryWrapper<MiOrderItemEntity>().eq("order_sn", orderSn));
                if(orderItemEntities.size() > 0){
                    for (MiOrderItemEntity orderItemEntity : orderItemEntities) {
                        // 找到goods_id
                        Integer goodsId = orderItemEntity.getGoodsId();
                        Integer count = orderItemEntity.getCount();
                        MiWareEntity miWareEntity =
                                miWareService.getOne(new QueryWrapper<MiWareEntity>().eq("goods_id", goodsId));
                        if(miWareEntity != null){
                            Integer stockLocked = miWareEntity.getStockLocked();
                            int newLocked = stockLocked - count;
                            if(newLocked <= 0){
                                newLocked = 0;
                            }
                            miWareEntity.setStockLocked(newLocked);
                            // 更新
                            boolean b1 = miWareService.updateById(miWareEntity);
                            if(!b1){
                                throw new MiException(ResultCode.ERROR1205.getStatus(), ResultCode.ERROR1205.getMessage());
                            }
                        }
                    }
                } else {
                    throw new MiException(ResultCode.ERROR1205.getStatus(), ResultCode.ERROR1205.getMessage());
                }
                boolean remove = miOrderItemService.remove(new QueryWrapper<MiOrderItemEntity>().eq("order_sn", orderSn));
                if(!remove){
                    throw new MiException(ResultCode.ERROR1205.getStatus(), ResultCode.ERROR1205.getMessage());
                }
                return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), "取消订单成功！");
            }
            throw new MiException(ResultCode.ERROR1205.getStatus(), ResultCode.ERROR1205.getMessage());
        } else {
            throw new MiException(ResultCode.ERROR1205.getStatus(), ResultCode.ERROR1205.getMessage());
        }
    }
}
